package cn.edu.sdjzu.xg11.dao;

import java.util.Collection;
import java.util.TreeSet;

import org.springframework.stereotype.Repository;

import cn.edu.sdjzu.xg11.domain.Degree;
import cn.edu.sdjzu.xg11.domain.Department;
import cn.edu.sdjzu.xg11.domain.Teacher;
import cn.edu.sdjzu.xg11.domain.Title;

@Repository
public final class TeacherDao {
	private static TeacherDao teacherDao = new TeacherDao();

	private TeacherDao() {
	}

	public static TeacherDao getInstance() {
		return teacherDao;
	}

	private static Collection<Teacher> teachers;
	static {

		Title assProf = new TitleDao().getTitle(2);
		Title lecture = new TitleDao().getTitle(3);

		Degree master = new DegreeDao().getDegree(2);

		Department misDept = new DepartmentDao().getDepartment(2);

		teachers = new TreeSet<Teacher>();
		Teacher teacher = new Teacher("佀同光", assProf, master, misDept);
		teachers.add(teacher);
		teachers.add(new Teacher("刘夏", lecture, master, misDept));
		teachers.add(new Teacher("王霞", assProf, master, misDept));
	}

	public Collection<Teacher> getTeachers() {
		return TeacherDao.teachers;
	}

	public Teacher getTeacher(Integer id) {
		Teacher desiredTeacher = null;
		for (Teacher teacher : teachers) {
			if (id.equals(teacher.getId())) {
				desiredTeacher = teacher;
				break;
			}
		}
		return desiredTeacher;
	}

	public boolean updateTeacher(Teacher teacher) {
		teachers.remove(teacher);
		return teachers.add(teacher);
	}

	public boolean addTeacher(Teacher teacher) {
		return teachers.add(teacher);
	}

	public boolean deleteTeacher(Integer id) {
		Teacher teacher = this.getTeacher(id);
		
		return this.deleteTeacher(teacher);
	}

	public boolean deleteTeacher(Teacher teacher) {
		return teachers.remove(teacher);
	}

	public static void main(String[] args) {
		System.out.println("========begin===============");
		TeacherDao dao = new TeacherDao();
		Collection<Teacher> teachers = dao.getTeachers();
		display(teachers);
		System.out.println("============update STG===========");
		Teacher teacher = dao.getTeacher(1);
		teacher.setName("STG");
		dao.updateTeacher(teacher);
		display(teachers);
		System.out.println("=========delete STG, 3==============");
		dao.deleteTeacher(teacher);
		dao.deleteTeacher(3);
		display(teachers);
		System.out.println("========卢文锋 ADD ===============");

		Title lecture = new TitleDao().getTitle(3);
		Degree master = new DegreeDao().getDegree(2);
		Department misDept = new DepartmentDao().getDepartment(2);

		
		Teacher teacher2 = new Teacher("卢文锋", lecture, master, misDept);
		System.out.println("new teacher===" + teacher2);
		dao.addTeacher(teacher2);
		display(teachers);
		System.out.println("=======================");
		System.out.println("teacher2====" + dao.getTeacher(2));
	}

	private static void display(Collection<Teacher> teachers) {
		for (Teacher teacher : teachers) {
			System.out.println(teacher);
		}
	}

}
